package com.ihome.framework.core.dubbo;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import com.ihome.framework.core.log.LogConst;
import com.ihome.framework.core.log.LogTools;

/**
 * 实现在dubbo调用的时候，在attachments中加上该次调用的uniqueId
 * 
 * @author zhengxiaohong
 */
@Activate(group = { Constants.CONSUMER, Constants.PROVIDER })
public class DubboTraceFilter implements Filter {

	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
		RpcContext context = RpcContext.getContext();
		Map<String, String> attachments = context.getAttachments();

		String uniqueId = attachments.get(LogConst.UID);

		if (StringUtils.isBlank(uniqueId)) {
			uniqueId = MDC.get(LogConst.UID);
		}

		if (StringUtils.isBlank(uniqueId)) {
			uniqueId = LogTools.generateUID();
		}
		context.setAttachment(LogConst.UID, uniqueId);
		MDC.put(LogConst.UID, uniqueId);
		return invoker.invoke(invocation);
	}

}
